<template>
  <div id="specMerge">
    <!-- 标本合并弹框 -->
    <el-dialog title="标本合并" draggable v-model="dialogVisibleMerge" v-if="dialogVisibleMerge" :v-loading="Sloading" :modal="false" :modal-append-to-body="false" :close-on-click-modal="false" :append-to-body="false" @closed="dialogClose(false)" width="650px" class="dialogMerge" destroy-on-close>
      <el-form ref="specMergeForm" :model="form" :rules="formRule" class="form-input-m" :inline-message="true" @submit.prevent label-width="60px">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-divider content-position="left">合并前</el-divider>
            <el-form-item label="工 作 组">
              <!-- <el-select v-model="form.sourceRptGroup.name" placeholder="请选择报告单元" @change="(val) => rptGroupChange(val, 'sourceRptGroup')" filterable clearable>
                <el-option v-for="item in rptGroups" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
              <el-select v-model="form.sourceRptGroup.selectChildWt.name" placeholder="请选择子报告单元" filterable clearable @change="selectChildWtChange($event, 'sourceRptGroup')">
                <el-option v-for="item in wtChilds" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select> -->
              <SelectWorkGroup :url="'/api/rptGroup/findRptGroup'" @getSelectedId="(val, val1) => rptGroupChange(val, val1, 'sourceRptGroup')" :isStoreRemember="false" />
            </el-form-item>
            <el-form-item label="标本日期">
              <el-date-picker v-model="form.sourceSampleda" type="date" :shortcuts="pickerOpts" placeholder="选择标本日期"> </el-date-picker>
            </el-form-item>
            <el-form-item label="标 本 号">
              <el-input v-model="form.sourceSampleNo" placeholder="请输入1,2,5-8等格式" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-divider content-position="left">合并后</el-divider>
            <el-form-item label="工 作 组">
              <!-- <el-select v-model="form.targetRptGroup.name" placeholder="请选择报告单元" @change="(val) => rptGroupChange(val, 'targetRptGroup')" filterable clearable>
                <el-option v-for="item in rptGroups" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
              <el-select v-model="form.targetRptGroup.selectChildWt.name" placeholder="请选择子报告单元" filterable clearable @change="selectChildWtChange($event, 'targetRptGroup')">
                <el-option v-for="item in wtChilds" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select> -->
              <SelectWorkGroup :url="'/api/rptGroup/findRptGroup'" @getSelectedId="(val, val1) => rptGroupChange(val, val1, 'targetRptGroup')" :isStoreRemember="false" />
            </el-form-item>
            <el-form-item label="标本日期">
              <el-date-picker v-model="form.targetSampleda" type="date" :shortcuts="pickerOpts" placeholder="选择标本日期"> </el-date-picker>
            </el-form-item>
            <el-form-item label="标 本 号">
              <el-input v-model="form.targetSampleNo" placeholder="请输入1,2,5-8等格式" clearable :disabled="targetSampleNoDisable"></el-input>
            </el-form-item>
            <el-form-item label-width="0">
              <vxe-checkbox v-model="form.autoMerge" :checked-value="1" :unchecked-value="0" @change="autoMergeChange">根据病人信息智能合并（病历号+姓名）</vxe-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form :model="form" class="form-input-m" :inline-message="true">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-divider content-position="left">合并内容</el-divider>
            <el-form-item>
              <vxe-checkbox v-model="form.mergePatInfo" label="病人资料" :checked-value="1" :unchecked-value="0" @change="checkboxChange($event, 'mergeTestDoctor')">病人资料</vxe-checkbox>
              <vxe-checkbox v-model="form.mergeTestDoctor" label="检验人员" :checked-value="1" :unchecked-value="0">检验人员</vxe-checkbox>
            </el-form-item>
            <el-form-item>
              <vxe-checkbox v-model="form.isAllItemDict" label="所有项目" :checked-value="1" :unchecked-value="0" @change="checkboxChange($event, 'mergeFile', ['isMoreItem'])">所有项目</vxe-checkbox>
              <vxe-checkbox v-model="form.mergeFile" label="图形信息" :checked-value="1" :unchecked-value="0">图形信息</vxe-checkbox>
            </el-form-item>
            <el-form-item class="selectItem">
              <vxe-checkbox v-model="form.isOneItemDict" label="单个项目" :checked-value="1" :unchecked-value="0" @change="singleChkChange">单个项目</vxe-checkbox>
            </el-form-item>
            <el-form-item v-if="form.isOneItemDict === 1 || form.isOneItemDict === '1'" class="selectItem" prop="itemNo">
              <el-select v-model="form.itemNo" placeholder="请选择项目" @change="itemDictChange($event, 'itemNo')" filterable clearable>
                <el-option v-for="item in itemDicts" :key="item.id" :label="item.itemNa" :value="item.itemNo"> </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item class="selectItem">
              <vxe-checkbox v-model="form.isMoreItem" label="组合项目" :checked-value="1" :unchecked-value="0">组合项目</vxe-checkbox>
            </el-form-item>
            <el-form-item prop="form.ansGroup" v-if="form.isMoreItem===1||form.isMoreItem==='1'">
              <el-select v-model="form.ansGroup.name" placeholder="请选择组合项目" @change="itemDictChange($event, 'anSGroup')" filterable clearable>
                <el-option v-for="item in mergeTemplates" :key="item.id" :label="item.templateName" :value="item.templateCode"> </el-option>
              </el-select>
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-divider content-position="left">合并方式</el-divider>
            <el-row>
              <el-col :span="12">
                <el-form-item>
                  <el-radio-group v-model="form.copy">
                    <el-radio :label="1">复制</el-radio>
                    <el-radio :label="0">移动</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-radio-group v-model="form.overwrite">
                    <el-radio :label="1">如果存在就覆盖</el-radio>
                    <el-radio :label="0">如果存在就取消</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item style="margin-top: 10px">
              <vxe-checkbox v-model="form.mergeByItemNo" :checked-value="1" :unchecked-value="0">按项目代号合并</vxe-checkbox>
            </el-form-item>
            <el-form-item style="margin-top: 10px">
              <vxe-checkbox v-model="form.isMergeSCO" :checked-value="1" :unchecked-value="0">合并S/CO值到目标报告单元结果列</vxe-checkbox>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!-- <el-divider content-position="left">说明</el-divider> -->
            <div class="explain">说明：标本号可以输入如:1,2,5-8等格式来表示多个标本。在同时合并多个标本的情况下，要确保合并前的标本个数和合并后的标本个数相等，否则系统无法一一对照进行合并;只有一种特殊情况可以进行一对多合并，那就是将一个标本复制到多个标本上。若存在多个带字母的标本，格式需为 1,P1,(P)3-(P)6</div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleMerge('specMergeForm')" :loading="Sloading">{{ Sloading ? '保存中 ...' : '确 定' }}</el-button>
          <el-button @click="dialogClose(false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, getCurrentInstance, onMounted, watch, provide, toRefs, computed } from 'vue';
import { IsEmpty, formatDateTime } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import SelectWorkGroup from './SelectWorkGroup.vue'; //报告单元引入下拉组件
import { AppStore } from '@/stores/store';

let { proxy } = getCurrentInstance();
const store = AppStore();
let props = defineProps({
  formMerge: {} as any,
  dialogVisible: { type: Boolean, default: false },
});

let pickerOpts = reactive([
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]);//TimePickerOpts;
let dialogVisibleMerge = ref(false); //标本合并
let rptGroupLoading = ref(false);
let Sloading = ref(false);
let targetSampleNoDisable = ref(false);
let rptGroups = reactive([]);
let wtChilds = reactive([]);
let itemDicts = reactive([]); //报告单元项目
let mergeTemplates = reactive([]); //组合项目
let form = reactive({
  sourceRptGroup: {
    id: null,
    code: '',
    name: ''
  },
  targetRptGroup: {
    id: null,
    code: '',
    name: ''
  },
  sourceSampleda: null, //合并前标本日期
  targetSampleda: null, //合并后标本日期
  sourceSampleNo: '', //合并前标本号
  targetSampleNo: '', //合并后标本号
  // mergeItems: [],//合并内容
  mergePatInfo: 0, //病人资料
  mergeTestDoctor: 0, //检验人员
  isAllItemDict: 1, //所有项目
  mergeFile: 0, //图形信息
  isOneItemDict: 0, //单个项目
  itemNo: '', //项目id
  isMoreItem: 0, //多个项目
  ansGroup: {
    id: null,
    name: '',
    details: [],
  }, //组合项目id
  copy: 1, //是否为复制，否则为移动
  overwrite: 0, //如果存在就覆盖，否则存在就取消
  isMergeSCO: 0, //合并S/CO值到目标报告单元结果列
  autoMerge: 0, //智能合并
  mergeByItemNo: 0, //按项目代号合并
  mergeMethods: [], //合并方式
});

let initialFormData = reactive({
  sourceRptGroup: {
    id: null,
    name: ''
  },
  targetRptGroup: {
    id: null,
    name: ''
  },
  sourceSampleda: null, //合并前标本日期
  targetSampleda: null, //合并后标本日期
  sourceSampleNo: '', //合并前标本号
  targetSampleNo: '', //合并后标本号
  // mergeItems: [],//合并内容
  mergePatInfo: 0, //病人资料
  mergeTestDoctor: 0, //检验人员
  isAllItemDict: 1, //所有项目
  mergeFile: 0, //图形信息
  isOneItemDict: 0, //单个项目
  itemNo: '', //项目id
  isMoreItem: 0, //多个项目
  ansGroup: {
    id: null,
    name: '',
    details: [],
  }, //组合项目id
  copy: 1, //是否为复制，否则为移动
  overwrite: 0, //如果存在就覆盖，否则存在就取消
  isMergeSCO: 0, //合并S/CO值到目标报告单元结果列
  autoMerge: 0, //智能合并
  mergeByItemNo: 0, //按项目代号合并
  mergeMethods: [], //合并方式
});
let formRule = reactive({
  sourceSampleNo: {
    required: true,
    message: '标本号不可为空',
    trigger: 'blur',
  },
  targetSampleNo: {
    required: true,
    message: '标本号不可为空',
    trigger: 'blur',
  },
});
defineExpose({
  initPage
});

/**初始化标本合并 */
function initPage(sampleda) {
  console.log('检验日期', sampleda);
  dialogVisibleMerge.value = true;
  //getRptGroups('sourceRptGroup');
  //getRptGroups('targetRptGroup');
  form.sourceRptGroup.code = null;
  form.sourceRptGroup.name = null;
  form.targetRptGroup.code = null;
  form.targetRptGroup.name = null;
  form.sourceSampleda = sampleda;
  form.targetSampleda = sampleda;
  getRptGroupItemDictList();
  getMergeTemplateList();
}

//获取报告单元
function getRptGroups(name) {
  rptGroupLoading.value = true;
  const url = '/api/rptGroup/findRptGroupList';
  const data = { keyWords: '' };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      rptGroups.length = 0; //res.items;
      Object.assign(rptGroups, res.data);
      form[name] = {
        id: rptGroups[0].id,
        name: rptGroups[0].name,
        selectChildWt: {
          id: null,
          name: '',
        },
      };
      rptGroupLoading.value = false;
    })
    .catch((err) => {
      rptGroupLoading.value = false;
    });
}

// 下拉列表改变【报告单元】
function rptGroupChange(val, val1, nameKey) {
  form[nameKey].code = val.value;
  form[nameKey].name = val1.value;
  getRptGroupItemDictList();
  getMergeTemplateList();
}

// 获取报告单元项目
function getRptGroupItemDictList() {
  if (IsEmpty(form.sourceRptGroup.code)) {
    return;
  }
  const url = '/lis/lab/item/findJoinLabItemDictList';
  const data = {
    rptGroup: form.sourceRptGroup.code,
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      itemDicts.length = 0;
      Object.assign(itemDicts, res.data);
    })
    .catch((err) => {
      //this.$alert(err.data.error.message, '提示');
    });
}
// 获取组合项目
function getMergeTemplateList() {
  if (form.sourceRptGroup && IsEmpty(form.sourceRptGroup.code)) {
    return;
  }
  const url = `/lab/template/getTemplateByRptGroup`;
  proxy.$http
    .get(url, { params: { rptGroup: form.sourceRptGroup.code } })
    .then((res: any) => {
      mergeTemplates.length = 0;
      Object.assign(mergeTemplates, res.data);
    })
    .catch((err) => {
      //this.$alert(err.data.error.message, '提示');
    });
}

// 下拉列表改变【项目】
function itemDictChange(val, name) {
  form[name] = val;
  if (name === 'anSGroup') {
    const res = mergeTemplates.find((item) => {
      return val === item.id;
    });
    form[name].details = res.details;
  }
}

// 单个项目选中状态改变
function isItemChange(event, arr) {
  if (event) {
    checkboxChange(event, '', arr);
    if (form.isOneItemDict && (form.isOneItemDict === 1 || form.isOneItemDict === '1')) {
      getRptGroupItemDictList();
    } else if (form.isMoreItem && (form.isMoreItem === 1 || form.isMoreItem === '1')) {
      getMergeTemplateList();
    }
  }
}
// 合并内容多选按钮改变状态
function checkboxChange(event, name, arr) {
  if (!IsEmpty(name)) {
    form[name] = event ? 1 : 0;
  }
  if (event && arr && (arr as any).length > 0) {
    arr.forEach((element) => {
      form[element] = !event ? 0 : 1;
    });
    if (event) {
      form.isOneItemDict = 0;
    }
  }
}
/**单个项目复选框选择改变 */
function singleChkChange() {
  form.isAllItemDict = 0;
  form.mergeFile = 0;
}
// 智能合并 多选按钮状态改变
function autoMergeChange(event) {
  if (event && event.checked) {
    form.mergePatInfo = 0;
    form.mergeTestDoctor = 0;
    form.targetSampleNo = '';
    targetSampleNoDisable.value = true;
  } else {
    if (targetSampleNoDisable.value) {
      targetSampleNoDisable.value = false;
    }
  }
}
// 确定合并
function handleMerge(formName) {
  const el: any = proxy.$refs[formName];
  el.validate(async (valid) => {
    if (!valid) {
      return false;
    }
    Sloading.value = true;
    const url = '/lab/maininfo/mergeTestList';
    let data = {
      sourceRptGroupId: form.sourceRptGroup.code,
      sourceSampleNo: form.sourceSampleNo,
      sourceSampleda: formatDateTime(form.sourceSampleda, 'yyyy-MM-dd') + ' 00:00:00',
      targetRptGroupId: form.targetRptGroup.code,
      targetSampleNo: form.targetSampleNo,
      targetSampleda: formatDateTime(form.targetSampleda, 'yyyy-MM-dd') + ' 00:00:00',
      mergePatInfo: form.mergePatInfo,
      mergeFile: form.mergeFile,
      mergeTestDoctor: form.mergeTestDoctor,
      itemDictCodes: [],
      overwrite: form.overwrite,
      copy: form.copy,
      autoMerge: form.autoMerge,
      mergeByItemNo: form.mergeByItemNo,
      isAllItemDict: form.isAllItemDict,//合并所有项目
      isOneItemDict: form.isOneItemDict,
      itemNo: form.itemNo

    };
    // console.log(form);
    // if (!form.isAllItemDict) {
    //   if (form.isOneItemDict) {
    //     data.ansIds.push(form.ans.id);
    //   } else if (form.isMoreItem) {
    //     form.ansGroup.details.forEach((item) => {
    //       data.ansIds.push(item.ansId);
    //     });
    //   }
    // }

    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
          VxeMessage('合并成功', VxeNotifyType.success);
          store.setMergeTestListFinish(`${new Date().valueOf()}`);
        }
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 400) {
          VxeMessage(res.status.msg ? res.status.msg : '合并失败', VxeNotifyType.error);
        }
        //this.$emit('handleClose', dialogVisibleMerge.value, true);
        Sloading.value = false;
      })
      .catch((err) => {
        Sloading.value = false;
        //NotifyMessage(err.data.error.message, NotifyType.error, this, 5000);
      });
  });
}
// 关闭弹框
function dialogClose() {
  Object.assign(form, initialFormData)
  dialogVisibleMerge.value = false;
  //this.$emit('handleClose', dialogVisibleMerge.value, false);
}
//#region  【组件】弹框选择
let visibleBysourceRptGroup = ref(false); //合并前报告单元
let wTRequestUrl = ref('/api/lims/application-types');
let visibleByapplicationEmergencyDegree = ref(false); //紧急程度
let applicationEmergencyDegreeRequestUrl = ref('/api/lims/application-emergency-degrees');
let enterIndex = ref(0);

//确定选择
function ConfirmByClick(row, name) {
  if (!IsEmpty(name)) {
    form[name].id = row.id;
    form[name].name = row.name;
  }

  const ele: any = proxy.$refs[name + 'InputElemt'];
  ele.focus();
  this['visibleBy' + name] = false;
}

//选择输入框获取焦点
function showDataBySelect(name) {
  this.enterIndex = 0;
  const ele: any = proxy.$refs[name + 'CompElemt'];
  ele.pageIndex = 1;
  ele.selectedItem.name = '';
  ele.findList();
}

//按回车键-列表的第一项
async function onEnterSelect(value, name) {
  const ele: any = proxy.$refs[name + 'CompElemt'];
  this.enterIndex++;
  if (this.enterIndex === 1) {
    if (ele.selectedItem) {
      ele.pageIndex = 1;
      ele.selectedItem.name = value;
      const eleFindList: any = await ele.findList();
      if (eleFindList.status) {
        ele.selectRow();
      }
    }
  } else if (this.enterIndex === 2) {
    if (ele.tableList.length === 0) {
      this.enterIndex = 0;
      NotifyMessage('未查询到数据', NotifyType.warning, this, 5000);
      return;
    }
    ele.ConfirmByClick(ele.tableList[0], name);
    const eleInput: any = proxy.$refs[name + 'InputElemt'];
    eleInput.blur();
    this['visibleBy' + name] = false;
  } else {
    this.enterIndex = 0;
    NotifyMessage(
      '请先把光标定位到输入框',
      NotifyType.error,
      this,
      5000
    );
  }
}
//#endregion
</script>
<style lang="scss" scoped>
#specMerge {
  // 标本合并弹框
  .el-dialog__wrapper.dialogMerge {
    right: auto;
    bottom: auto;
    top: 15vh;
    left: 250px;
    box-shadow: 0 1px 5px rgb(0 0 0 / 30%);

    :deep(.el-dialog) {
      margin: 0 !important;
    }

    .el-form-item {
      position: relative;
      margin-bottom: 5px;

      :deep(.el-form-item__content) {
        line-height: 28px;
        white-space: pre-line;
        word-wrap: break-word;
      }

      .el-radio {
        display: block;
      }

      .el-radio:last-child {
        margin-top: 10px;
      }
    }

    :deep(.explain) {
      white-space: initial;
      line-height: 1.5em;
      // font-size: 14px;
      color: $font-color-3;
      padding-top: 10px;
      margin-top: 10px;
    }

    :deep(.selectItem .el-input) {
      width: 150px;
      margin-left: 10px;
    }
  }
}
</style>
